package com.example.tvscreendisplay;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WebActivity extends FragmentActivity {

    private WebView webview;
    private Button refreshbutton;

    private static String url = "http://hdwq.wine-manu.top/prod-api/manu/pubToolScreen/screenInfoById/";

    private SharedPreferences SP;
    private SharedPreferences.Editor editor;


    //异步(**选取Android OS的handler**)
    private Handler mHandler = new Handler(Looper.myLooper()){

        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 100){
                String data = (String) msg.obj;

                //将json数据转为数据实体类(JAVA 对象)
                ScreenInfoDetail screenInfoDetail = new Gson().fromJson(data, ScreenInfoDetail.class);

                webview.setWebViewClient(new WebViewClient());

                //清除登录网页产生的缓存
                clearWebViewCache();


                if( screenInfoDetail.getData() != null){

                    webview.loadUrl(screenInfoDetail.getData().getDescription());
                    //webview.loadUrl("javascript:window.location.reload(true)");
                    //webview.reload();

//                    webview.loadUrl("https://www.baidu.com");

                } else {

                    webview.loadUrl("https://www.bai.com");

                }




            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        webview = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = webview.getSettings();
        //让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);

        refreshbutton = (Button) findViewById(R.id.refreshbutton);

        //refreshbutton.requestFocus();

        //实例化对象(SharedPreferences 文件的名称与MainActivity中的SharedPreferences要一致，都为data_storage。否则无法获取Id值)
        SP = getSharedPreferences("data_storage", Context.MODE_PRIVATE);
        editor = SP.edit();

        getHttpDataDetail();

        // 设置按键事件监听器
        //setKeyListener();

        refreshbutton.setOnClickListener(mOnClickListener);



    }

    private void getHttpDataDetail() {

        //获取MainActivity的点击事件传递过来的数据
        //Intent intent = getIntent();

        String id = SP.getString("Id","");

        if (!id.isEmpty()) {

            //Log.d("----getId----","getId:"+id);

            //创建OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            //构建Request对象
            Request request = new Request.Builder()
                    .url(url+id)
                    .get()
                    .build();
            //通过OkHttpClient对象和Request对象来构建Call对象

            Call call = client.newCall(request);
            //通过Call对象的enqueue（Callback）方法来执行异步请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.d("--------","onFailure:"+e.toString());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                    //Log.d("--------","onResponse:"+response.body().string());

                    String data = response.body().string();

                    //不能直接在这里操作UI，因为这是一个耗时操作，要使用handler
                    Message message = new Message();
                    message.what = 100;
                    message.obj = data;

                    //发送
                    mHandler.sendMessage(message);

                }
            });

        } else {

            Log.d("----Failure----","Failure");

        }


    }

    //清除登录网页产生的缓存
    private void clearWebViewCache() {
        webview.clearCache(true);
        CookieManager.getInstance().removeAllCookies(null);
    }

    @Override
    public void onBackPressed(){
        if (webview.canGoBack()){
            webview.goBack();
        }else {
            super.onBackPressed();
        }
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.refreshbutton) {

                getHttpDataDetail();

                Toast.makeText(WebActivity.this, "已完成刷新", Toast.LENGTH_LONG).show();

            }

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (refreshbutton.hasFocus()) {
                webview.requestFocus();
                refreshbutton.setVisibility(View.GONE);
                //refreshbutton.clearFocus();
                return true;
            }

            if (webview.hasFocus()) {
                refreshbutton.setVisibility(View.VISIBLE);
                refreshbutton.requestFocus();
                 //refreshbutton.clearFocus();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }



    private void setKeyListener() {
        // 处理遥控器按键事件
        webview.setOnKeyListener((v, keyCode, event) -> {

            Log.d("KeyEventDebug", "Received keyCode: " + keyCode);

            if (keyCode == KeyEvent.KEYCODE_MENU) {

                Log.d("ButtonVisibility", "Before: Refresh button visibility = " + (refreshbutton.getVisibility() == View.VISIBLE? "VISIBLE" : "GONE"));

                // 菜单按钮按下，切换刷新按钮的可见性
                if (refreshbutton.getVisibility() != View.VISIBLE) {

                    refreshbutton.setVisibility(View.VISIBLE);
                    refreshbutton.requestFocus();

                }
                Log.d("ButtonVisibility", "After: Refresh button visibility = " + (refreshbutton.getVisibility() == View.VISIBLE? "VISIBLE" : "GONE"));
                return true;
            }

            return false;
        });
    }

}
